package com.gogowan.agroenterprise.widget;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.PicturesInfo;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PicturesAdapter extends BaseAdapter {

	private List<PicturesInfo> list;
	private Context context;

	private List<Drawable> listDrawable;
	private String path;
	private GridView gridView;

	// private SharedPreferences sharedPreferences;

	public PicturesAdapter(Context context, List<PicturesInfo> list,
			GridView gridView) {
		this.context = context;
		this.gridView = gridView;
		setList(list);
		listDrawable = new ArrayList<Drawable>();

		/*
		 * sharedPreferences = context.getSharedPreferences("LoginINfo",0);
		 * String dataStr = sharedPreferences .getString("saveLoginInfo", null);
		 * if (!Utils.isEmpty(dataStr)) { LoginResultInfo loginResultInfo =
		 * (LoginResultInfo)Utils.fromJSON(dataStr, LoginResultInfo.class);
		 * String path = loginResultInfo.getFtpulr(); if (Utils.checkHttp(path))
		 * { this.path = path; } }
		 */
	}

	public void setList(List<PicturesInfo> list) {
		if (list != null) {
			this.list = list;
			this.list.add(null);
		} else {
			this.list = new ArrayList<PicturesInfo>();
			this.list.add(null);
			return;
		}

		for (int i = 0; i < list.size(); i++) {
			PicturesInfo picturesInfo = list.get(i);
			if (picturesInfo != null) {
				listDrawable.add(i, null);
				if (path == null || path.equals("")) {
					GetPicAsync getPicAsync = new GetPicAsync(i);
					getPicAsync.execute(picturesInfo.getRequestUrl());
				} else {
					Drawable drawable = Drawable.createFromPath(path);
					listDrawable.set(i, drawable);
					PicturesAdapter.this.notifyDataSetChanged();

				}
			}
		}

		/*
		 * for (int i = 0; i < list.size(); i++) { PicturesInfo picturesInfo =
		 * list.get(i); if (picturesInfo != null) { GetPicAsync getPicAsync =
		 * new GetPicAsync(i);
		 * getPicAsync.execute(picturesInfo.getRequestUrl()); } }
		 */

		// this.notifyDataSetChanged();
	}

	public List<PicturesInfo> getDataList() {
		List<PicturesInfo> list = this.list;
		if (list.size() == 0) {

		} else {
			list.remove(list.size() - 1);
		}
		return list;
	}

	public List<PicturesInfo> getList() {
		return this.list;
	}

	/**
	 * 添加
	 * 
	 * @param picturesInfo
	 */
	public void addPicturesInfo(PicturesInfo picturesInfo) {
		if (list.size() > 6) {
			Toast.makeText(context, "不能添加更多图片", Toast.LENGTH_SHORT).show();
			return;
		}
		if (list != null) {
			// list最后一条空的赋值
			list.set(list.size() - 1, picturesInfo);
			list.add(null);
			// 先获取图片，再刷新
			if (picturesInfo != null) {

				try {
					File sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
					path = sdDir.getPath() + "/AgricultureSystem/Image/"
							+ picturesInfo.getSurl();
					// path =
					// "/mnt/sdcard/AgricultureSystem/Image/"+picturesInfo.getSurl();
					Drawable drawable = Drawable.createFromPath(path);
					if (drawable != null) {
						listDrawable.add(list.size() - 2, null);
						listDrawable.set(list.size() - 2, drawable);
						// handler.sendEmptyMessage(1);
						PicturesAdapter.this.notifyDataSetChanged();
					} else {
						Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT)
								.show();
						try {
							del(list.size() - 2);
						} catch (Exception e) {
						}
					}

				} catch (Exception e) {
					Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT)
							.show();
					e.printStackTrace();
					try {
						del(list.size() - 2);
					} catch (Exception e2) {
					}
				}
				// TODO
				// listDrawable.set(list.size()-2,
				// Drawable.createFromPath(path));
				// 测试,需要改回去的
				// getPicAsync.execute( picturesInfo.getSurl());
			}
			// this.notifyDataSetChanged();
		}
	}

	/**
	 * 删除一个
	 * 
	 * @param position
	 */
	public boolean del(int position) {
		try {
			list.remove(position);
			listDrawable.remove(position);
			this.notifyDataSetChanged();
		} catch (IndexOutOfBoundsException e) {
			return false;
		} catch (UnsupportedOperationException e) {
			return false;
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	/**
	 * 编辑图片描述
	 * 
	 * @param string
	 *            新的图片描述
	 * @param position
	 *            编辑的位置
	 */
	public void editDiscription(String string, int position) {
		try {
			PicturesInfo picturesInfo = list.get(position);
			picturesInfo.setDescription(string);
			list.set(position, picturesInfo);
			this.notifyDataSetChanged();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int getCount() {
		if (list != null) {
			return list.size();
		}
		return 0;
	}

	@Override
	public PicturesInfo getItem(int position) {
		if (list != null) {
			return list.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			final LayoutInflater inflater = LayoutInflater.from(context);
			convertView = (View) inflater.inflate(
					R.layout.pictures_grid_view_item, null);

			holder = new ViewHolder();
			holder.img = (ImageView) convertView
					.findViewById(R.id.pictures_gridview_item_image);
			holder.progressBar = (ProgressBar) convertView
					.findViewById(R.id.pictures_gridview_item_pb);
			holder.text = (TextView) convertView
					.findViewById(R.id.pictures_gridview_item_text);
			// holder.text.setFilters(new InputFilter[]{new
			// InputFilter.LengthFilter(245)});
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		// layout.setClickable(false);
		if (list != null && list.size() > 0 && listDrawable != null
				&& listDrawable.size() > 0) {
			PicturesInfo picturesInfo = list.get(position);
			if (picturesInfo != null) { // &&
										// !Utils.isEmpty(picturesInfo.getUrl())
				try {
					Drawable drawable = listDrawable.get(position);
					if (drawable != null) {
						holder.img.setImageDrawable(drawable);
						holder.text.setText(picturesInfo.getDescription());
					}
				} catch (Exception e) {
					Log.d("setText", e.getLocalizedMessage());
				}

			} else {
				final LayoutInflater inflater = LayoutInflater.from(context);
				convertView = (View) inflater.inflate(
						R.layout.pictures_grid_view_item, null);

				holder = new ViewHolder();
				holder.img = (ImageView) convertView
						.findViewById(R.id.pictures_gridview_item_image);
				holder.progressBar = (ProgressBar) convertView
						.findViewById(R.id.pictures_gridview_item_pb);
				holder.text = (TextView) convertView
						.findViewById(R.id.pictures_gridview_item_text);
				convertView.setTag(holder);
				if (picturesInfo == null) {
					holder.img.setImageResource(R.drawable.hs_image_paizhao);
				}
			}
		} else {
			holder.img.setImageResource(R.drawable.hs_image_paizhao);
		}
		adaptHeight();
		return convertView;
	}

	public void adaptHeight() {
		try {
			int height = Integer.parseInt(context
					.getString(R.string.grid_view_height));
			// int height = 120;
			// 自适应gridview高度
			double h = ((double) (list.size() + 1)) / ((double) 4);// 计算行数
			int hh = (int) Math.ceil(h);
			LayoutParams param = gridView.getLayoutParams();
			param.height = height * hh;// 设置固定高
			gridView.setLayoutParams(param);
		} catch (NumberFormatException nfe) {

		} catch (Exception e) {

		}
	}

	static class ViewHolder {
		ImageView img;
		ProgressBar progressBar;
		TextView text;
	}

	public byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
		return outStream.toByteArray();
	}

	public void clear() {
		list.clear();
		this.list = new ArrayList<PicturesInfo>();
		this.list.add(null);
		this.notifyDataSetChanged();
	}

	/**
	 * 获取图片并显示
	 * 
	 * @author Administrator
	 * 
	 */
	public class GetPicAsync extends MyAsyncTask {

		private int location;
		private Drawable drawable = null;

		public GetPicAsync(int location) {
			this.location = location;
			listDrawable.add(location, null);
		}

		@Override
		protected Object doInBackground(Object... params) {

			// byte[] bytes=null;
			try {
				String path = (String) params[0];
				URL url = new URL(path);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setConnectTimeout(5 * 1000);
				conn.setRequestMethod("GET");
				InputStream inStream = conn.getInputStream();
				if (conn.getResponseCode() == 200) {
					drawable = Drawable.createFromStream(inStream, path);
					// bytes=Utils.input2byte(inStream);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(Object res) {
			try {
				// Drawable drawable = (Drawable) res;
				if (drawable != null) {
					listDrawable.set(location, drawable);
					// handler.sendEmptyMessage(1);
					PicturesAdapter.this.notifyDataSetChanged();
				} else {
					Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT)
							.show();
					/*
					 * try { del(list.size()-2); } catch (Exception e) { //
					 * TODO: handle exception }
					 */
				}
			} catch (Exception e) {
				Toast.makeText(context, "图片加载失败！", Toast.LENGTH_SHORT).show();
				/*
				 * try { del(list.size()-2); } catch (Exception e2) { // TODO:
				 * handle exception }
				 */
			}
			// imageView.setImageDrawable(drawable);
			// progressBar.setVisibility(View.GONE);
			// Message msg=new Message();
			// msg.what=0;
			// Bundle mBundle=new Bundle();
			// mBundle.putSerializable("holder",holder);
			// mBundle.putByteArray("bytes", (byte[])res);
			// mBundle.putString("path", path);
			// msg.setData(mBundle);
			// handler.handleMessage(msg);
			// mBundle.clear();
			/*
			 * progressBar.setVisibility(View.GONE); byte[] data = (byte[]) res;
			 * if (data != null) { Bitmap bitmap =
			 * BitmapFactory.decodeByteArray(data, 0, data.length);
			 * imageView.setImageBitmap(bitmap); }
			 */
			super.onPostExecute(null);
		}

	}
}